<?php /* УТФ-8:fix */

class SPIcontroller__songnvideo__manage extends SPIcontroller__songnvideo
{
    public $CONTENT_MODES = array(); // may use be other modules !

    public function __construct()
    {
        parent::__construct();

        $this->CONTENT_MODES = array(
            'song' => array(
                'song'               => SPI::I('lang')->songnvideo->typename['song'],
            ),
            'video' => array(
                'video'               => SPI::I('lang')->songnvideo->typename['video'],
            ),
        );

        return;
    }

    public function gen_menu()
    {
        $menuitems = array();

        $in_topic = SPI::I('var')->get('topic');
        $in_tmode = SPI::I('var')->get('tmode');

        $toolbar_attrs = array(
            'song'     => array( 'toolbar'=>'MAIN',  'align_prior'=>3 ),
            'video'    => array( 'toolbar'=>'MAIN',  'align_prior'=>3 ),
        );

        foreach( array_keys( $this->CONTENT_MODES ) as $one_tmode )
        {
            $menuitems[ $toolbar_attrs[$one_tmode]['toolbar'] ][] = array(
                'access'        => array( SPI_IAM_PERM_ADMIN ),
                'link'          => $this->pack_link( $one_tmode ),
                'icon'          => "songnvideo__manage_{$one_tmode}.gif",
                'name'          => SPI::I('lang')->songnvideo->{"menu_{$one_tmode}"},
                'is_active'     => $in_topic == $this->CONTROLLER_ID && $in_tmode == $one_tmode,
                'align_prior'   => $toolbar_attrs[$one_tmode]['align_prior'],
            );
        }

        return $menuitems;
    }

    public function pack_link( $mode = null, $vars = null )
    {
        return SPIc::I('manage')->link->pack( $this->CONTROLLER_ID, $mode, $vars );
    }

    public function exec( & $content )
    {
        $data = array();

        $data['topic']  = SPI::I('var')->get('topic');
        $data['tmode']  = SPI::I('var')->get('tmode');
        $data['action'] = SPI::I('var')->get('action');

        if( SPI::I('Iam')->is_permit( SPI_IAM_PERM_ADMIN ) !== true )
        {
            return false;
        }

        if( in_array( $data['tmode'], array_keys( $this->CONTENT_MODES ) ) === false )
        {
            return false;
        }

        switch( $data['action'] )
        {
            default:
            {
                $data['action'] = 'view';
            }
            case 'view':
            {
                if( $this->exec_view( $content, $data ) === false )
                {
                    return false;
                }
                break;
            }

            case 'sort':
            {
                $this->exec_sortdata( $content, $data );
                break;
            }

            case 'insert':
            case 'modify':
            {
                $this->exec_savedata( $content, $data ); # => die by json-data response
            }

            case 'form':
            {
                if( $this->exec_form( $content, $data ) === false )
                {
                    return false;
                }
                break;
            }
        }

        $content['data'] = $data;

        return true;
    }

    private function exec_view( & $content, & $data, $is_recursive_exec = false )
    {
        $data['title']    = SPI::I('lang')->songnvideo->{"title_{$data['tmode']}"};
        $data['subtitle'] = SPI::I('lang')->manage->viewmode_list;
        $data['template'] = 'songnvideo/view.tpl';

        $data['CONTENT_MODES'] = $this->CONTENT_MODES;

        $data['link_newitem'] = $this->pack_link( $data['tmode'], array( 'action'=>'form' ) );
        
		$data['link_sort_top']    = $this->pack_link( $data['tmode'], array( 'action'=>'sort', 'sort_on'=>'top' ) );
		
		if($data['tmode'] == 'song'){
			$data['link_sort_new']    = $this->pack_link( $data['tmode'], array( 'action'=>'sort', 'sort_on'=>'new' ) );
		}
        // --------------------------------------------------------------------

        $action_do = SPI::I('var')->get('action_do' );
		
        if( $is_recursive_exec === false) // if $is_recursive_exec == true --> don't need to ReExecute action
		
        if( in_array( $action_do, array( 'activity_top_on', 'activity_new_on', 'activity_off', 'delete'  ) ) === true )
		
        {
            $id_list = SPI::I('var')->get( 'multiselect' );
            
            if( is_array( $id_list ) === false )
            {
                $id_list[] = SPI::I('var')->get( 'iid' );
            }

            foreach( $id_list as $item_id )
            {
                $item_id = (int) $item_id;

                if( $item_id == 0 )
                {
                    continue;
                }

                switch( $action_do )
                {
					case 'activity_top_on':  SPIm::I('songnvideo')->manage->set_activity( 'on_top', $item_id ); break;
					case 'activity_new_on':  SPIm::I('songnvideo')->manage->set_activity( 'on_new', $item_id ); break;
                    case 'activity_off': SPIm::I('songnvideo')->manage->set_activity( 'off', $item_id ); break;
                    case 'delete':
                    {
                        SPIm::I('songnvideo')->manage->delete( $item_id );
                        SPIc::I('media')->manage->delete_group( $this->MEDIA_PHOTO_GID, $item_id );
                        SPIc::I('media')->manage->delete_group( $this->MEDIA_AUDIO_GID, $item_id );
                        SPIc::I('media')->manage->delete_group( $this->MEDIA_VIDEO_GID, $item_id );
                        break;
                    }
                }
            }
            unset( $id_list);
			
            SPIc::I('manage')->notifier->set_message( $content, true, SPI::I('lang')->notifier->msg_operation_complite );
        }
		
        if( in_array( $action_do, array( 'activity_top_on', 'activity_new_on', 'activity_off', 'set_sort_order' ) ) === true )
        {
            $new_index = false;
			
			if( in_array( $action_do, array( 'activity_top_on', 'activity_new_on', 'activity_off' ) ) === true )
            {
                $new_sort_order = array();
				$list_off = $this->get_by_status(0);
				$list_top = $this->get_by_status(1);
				$list_new = $this->get_by_status(2);
				
				$qres = SPIm::I('songnvideo')->manage->select( $data['tmode'], null, array( 'field'=>'order_index', 'dir'=>'+' ) );
                while( $itemtmp = $qres->fetch() )
                {
                    if( $itemtmp['order_index'] === null )
                    {
                        break;
                    }
                    $new_sort_order[] = $itemtmp['id'];
				    $new_index = true;
                }		
            }
            else
            {
                $new_sort_order = trim( SPI::I('var')->get('new_sort_order'), ',' );
                $new_sort_order = explode( ',', $new_sort_order );

                SPIc::I('manage')->notifier->set_message( $content, true, SPI::I('lang')->notifier->msg_modify_complite );
            }

            if( count( $new_sort_order ) > 0 )
            {
				$sort_on = SPI::I('var')->get('sort_on');				
				
                SPIm::I('songnvideo')->manage->reset_order_indexes( $data['tmode'],$sort_on );

				if($new_index === true){
					foreach( $new_sort_order as $sort_item_id )
					{
						if(isset($list_off[$sort_item_id])){
							$index = $list_off[$sort_item_id];
						}
						elseif(isset($list_top[$sort_item_id])){
							$index = $list_top[$sort_item_id];
						}
						else{
							$index = $list_new[$sort_item_id];
						}
						
						SPIm::I('songnvideo')->manage->modify( $sort_item_id, array( 'order_index'=>$index ) );						
					}					
					switch($action_do){
						case 'activity_top_on':
							$index = SPIm::I('songnvideo')->manage->getNextOrderIndex( 1 );
						break;
						case 'activity_new_on':
							$index = SPIm::I('songnvideo')->manage->getNextOrderIndex( 2 );
						break;
						case 'activity_off':
							$index=-1;
						break;
					}
					
					SPIm::I('songnvideo')->manage->modify( $item_id, array( 'order_index'=>$index ) );	
				}
				else{
					$index = 1;
					foreach( $new_sort_order as $sort_item_id )
					{
						SPIm::I('songnvideo')->manage->modify( $sort_item_id, array( 'order_index'=>$index++ ) );
					}
				}
            }
        }

        // --------------------------------------------------------------------
        // Make notifications by 'action_complite' value

        switch( SPI::I('var')->get('action_complite') )
        {
            case 'insert': SPIc::I('manage')->notifier->set_message( $content, true, SPI::I('lang')->notifier->msg_modify_complite ); break;
            case 'modify': SPIc::I('manage')->notifier->set_message( $content, true, SPI::I('lang')->notifier->msg_modify_complite ); break;
        }

        // --------------------------------------------------------------------
        // Filter objects [stdobj]

        $stdobj_baseurl = $this->pack_link( $data['tmode'], array( 'action'=>'view' ) );

        $content['stdobj']['f_search'] = SPIc::I('manage')->stdobj->filter(
            "{$data['topic']}:{$data['tmode']}",
            "search",
            $stdobj_baseurl
        );

        // --------------------------------------------------------------------
        // Order fields [stdobj]

        $orderfields_array = array( 'order_index+', 'name+', 'id+' );

        $content['stdobj']['order'] = SPIc::I('manage')->stdobj->order(
            "{$data['topic']}:{$data['tmode']}",
            $stdobj_baseurl,
            $orderfields_array
        );

        // --------------------------------------------------------------------

        $qresult = SPIm::I('songnvideo')->manage->select(
            $data['tmode'],
            $content['stdobj']['f_search']['value'],
            $content['stdobj']['order']['current']
        );

        if( $qresult === false )
        {
            return false;
        }
        
        $data['items_count'] = $qresult->num_rows();

        // --------------------------------------------------------------------
        // Pager [stdobj]

        $content['stdobj']['pager'] = SPIc::I('manage')->stdobj->pager(
            "{$data['topic']}:{$data['tmode']}",
            $stdobj_baseurl,
            $data['items_count'],
            100
        );

        // --------------------------------------------------------------------
        // Generate List

        $qresult->seek( $content['stdobj']['pager']['firstitem_index'] );
        $qresult->set_manual_limit( $content['stdobj']['pager']['items_per_page'] );

        $data['items'] = array();

        while( $item = $qresult->fetch() )
        {
            $item['preview'] = SPIm::I('media')->get_public_sourceByIndexOld(
                $this->MEDIA_PHOTO_GID, $item['id'], 1,
                array( 'mode' => 'preview' )
            );

            $item['pubdate'] = strftime( '%d.%m.%Y', strtotime( $item['pubdate'] ) );

            $item['link_modify'] = $this->pack_link( $data['tmode'], array( 'action'=>'form', 'iid'=>$item['id'] ) );
            $item['link_delete'] = $this->pack_link( $data['tmode'], array( 'action'=>'view', 'action_do'=>'delete', 'iid'=>$item['id'] ) );

			
			$item['link_activity_top_on'] = $this->pack_link( $data['tmode'], array( 'action'=>'view', 'action_do'=>'activity_top_on', 'iid'=>$item['id'] ) );
			$item['link_activity_new_on'] = $this->pack_link( $data['tmode'], array( 'action'=>'view', 'action_do'=>'activity_new_on', 'iid'=>$item['id'] ) );
			$item['link_activity_off'] = $this->pack_link( $data['tmode'], array( 'action'=>'view', 'action_do'=>'activity_off', 'iid'=>$item['id'] ) );
		
            $data['items'][ $item['id'] ] = $item;
        }
        $qresult->close();

        if( count( $data['items'] ) == 0 && $data['items_count'] != 0 && $is_recursive_exec === false )
        {
            // Reset page index to number '1'
            SPIc::I('manage')->stdobj->pager_reset( "{$data['topic']}:{$data['tmode']}" );

            // Recursive run
            return $this->exec_view( $content, $data, true );
        }

        if( $data['tmode'] == 'song' )
        {
            $content['top_items_count'] = SPIm::I('songnvideo')->manage->get_songs_in_top();
        }
        else
        {
            $content['top_items_count'] = null;
        }

        // --------------------------------------------------------------------

        $data['formvars'] = array();
        $data['formvars']['tmode']  = $data['tmode'];
        $data['formvars']['action'] = $data['action'];

        $data['link_form_submit'] = $this->pack_link();
		
		

        // --------------------------------------------------------------------

        return true;
    }
	
	private function get_by_status($status)
	{	
		$queryres = SPIm::I('songnvideo')->manage->select_by_status($status);
		
		$list = array();
		
		while( $itemtmp = $queryres->fetch() )
		{
			$list[$itemtmp['id']] = $itemtmp['order_index'];
		}
		return $list;
	}

    private function exec_sortdata( & $content, & $data )
    {	
		$sort_ord = SPI::I('var')->get('sort_on');
		
		$data['sort_on'] = SPI::I('var')->get('sort_on');
		
        $data['title']    = SPI::I('lang')->songnvideo->{"title_{$data['tmode']}"};
        
		$data['template'] = 'songnvideo/sort.tpl';
		
		if( $sort_ord=='top' ) 
			$data['subtitle'] = 'Сортировка элементов Топа';
        else
			$data['subtitle'] = 'Сортировка элементов Новинок';

        $data['link_back'] = $this->pack_link( $data['tmode'] );

		$qresult = SPIm::I('songnvideo')->manage->select_for_sort( $data['tmode'], $sort_ord );
		
        // --------------------------------------------------------------------
        // Generate List

        $data['items'] = array();

        while( $item = $qresult->fetch() )
        {
            $item['preview'] = SPIm::I('media')->get_public_sourceByIndexOld(
                $this->MEDIA_PHOTO_GID, $item['id'], 1,
                array( 'mode' => 'preview' )
            );

            $data['items'][ $item['id'] ] = $item;
        }
        $qresult->close();

        // --------------------------------------------------------------------

        $data['formvars'] = array();
        $data['formvars']['tmode']  = $data['tmode'];
        $data['formvars']['action'] = 'view';
        $data['formvars']['action_do'] = 'set_sort_order';

        $data['link_form_submit'] = $this->pack_link();

        return true;
    }

    private function exec_form( & $content, & $data )
    {
        $data['title']    = SPI::I('lang')->songnvideo->{"title_{$data['tmode']}"};
        $data['subtitle'] = '';
        $data['template'] = 'songnvideo/form.tpl';

        $data['link_back'] = $this->pack_link( $data['tmode'] );

        $item_id = (int) SPI::I('var')->get( 'iid' );

        if( $item_id )
        {
            $data['formmode'] = 'modify';
            $data['subtitle'] = SPI::I('lang')->manage->viewmode_form_update;

            $item_fields = SPIm::I('songnvideo')->manage->get_by_id( $item_id );
        }
        else
        {
            $data['formmode'] = 'insert';
            $data['subtitle'] = SPI::I('lang')->manage->viewmode_form_newitem;

            $item_fields = array();
            $item_fields['pubdate'] = strftime( '%Y-%m-%d' );
        }

        if( $item_fields['pubdate'] !== null )
        {
            $item_fields['pubdate'] = strftime( '%m/%d/%Y', strtotime( $item_fields['pubdate'] ) );
        }

        $ext_editor = SPIc::I('widget')->spaw2->open();
        $ext_editor->addpage( 'description_ExtEditor', $item_fields['description'] );
        $item_fields['description_ExtEditor'] = $ext_editor->render();

        $content['item_fields'] = $item_fields;

        // --------------------------------------------------------------------

        if( count( $this->CONTENT_MODES[ $data['tmode'] ] ) > 1 )
        {
            $data['list_types'] = $this->CONTENT_MODES[ $data['tmode'] ];
        }
        elseif( count( $this->CONTENT_MODES[ $data['tmode'] ] ) == 1 )
        {
            $data['const_type'] = $data['tmode'];
        }

        // --------------------------------------------------------------------

        $cMedia = SPIc::I('media');

        $content['media_photo'] = $cMedia->manage->initialize(
            $this->MEDIA_PHOTO_GID,
            $item_id ? $item_id : null,
            array( $cMedia->PRESET_IMAGES ),
            array( 'limit' => 1 )
        );

        if( $data['tmode'] == 'song' )
        {
            $content['media_audio'] = $cMedia->manage->initialize(
                $this->MEDIA_AUDIO_GID,
                $item_id ? $item_id : null,
                array( $cMedia->TYPE_AUDIO_MP3 ),
               array( 'limit' => 1 )
            );
        }
        elseif( $data['tmode'] == 'video' )
        {
            $content['media_video'] = $cMedia->manage->initialize(
                $this->MEDIA_VIDEO_GID,
                $item_id ? $item_id : null,
                array( $cMedia->TYPE_VIDEO_FLV ),
                array( 'limit' => 1 )
            );
        }

        // --------------------------------------------------------------------

        $data['formvars'] = array();
        $data['formvars']['tmode']  = $data['tmode'];
        $data['formvars']['action'] = $data['formmode'];

        if( $item_id )
        {
            $data['formvars']['iid'] = $item_id;
        }
        else
        {
            $data['formvars']['media_photo_gid'] = $content['media_photo']['gid'];
            $data['formvars']['media_audio_gid'] = $content['media_audio']['gid'];
            $data['formvars']['media_video_gid'] = $content['media_video']['gid'];
        }

        $data['link_form_submit'] = $this->pack_link();

        // --------------------------------------------------------------------

        return true;
    }

    private function exec_savedata( & $content, & $data )
    {
        if( in_array( $data['action'], array( 'insert', 'modify' ) ) === false )
        {
            trigger_error( 'Undefined action ('.$data['action'].')', E_USER_ERROR );
        }

        // --------------------------------------------------------------------

        if( $data['action'] == 'insert' )
        {
            $item_id = null;
        }
        else # modify
        {
            $item_id = (int) SPI::I('var')->get('iid');
        }

        $in_values = SPI::I('var')->get('field');

        // --------------------------------------------------------------------

        $validator = SPIc::I('validator')->open();

        $validator->add_rule( 'workstatus',     'integer[0:1]' );
        $validator->add_rule( 'name',           'string[1:255]' );

        if( $data['tmode'] == 'song' )
        {
            $validator->add_rule( 'anons',          'string[1:255]' );
        }
        elseif( $data['tmode'] == 'video' )
        {
            $validator->add_rule( 'anons',          'string[0:255]' ); // YouTube code
        }

        list( $status, $validator_data ) = $validator->exec( $in_values );

        if( $status === false )
        {
            $response = array();
            $response['status'] = 'error';
            $response['error_messages'] = $validator_data; // as errors
            SPIv::I('json')->render($response);
            die();
        }

        // --------------------------------------------------------------------
        // Pre insert | modify actions

        $in_values = $validator_data; // as parsed values
        $in_values['type'] = $data['tmode'];

        // --------------------------------------------------------------------
        // Do insert | modify

        if( $data['action'] == 'insert' )
        {
            $status = SPIm::I('songnvideo')->manage->insert( $in_values );

            if( $status !== false )
            {
                $item_id = $status;
                $status = true;
            }
        }
        else # modify
        {
            $status = SPIm::I('songnvideo')->manage->modify( $item_id, $in_values );
        }

        // --------------------------------------------------------------------

        if( $status === false )
        {
            $response = array();
            $response['status'] = 'error_alert';

            if( $data['action'] == 'insert' )
            {
                $response['error_message'] = 'При вставке данных возникла ошибка!';
            }
            else
            {
                $response['error_message'] = 'При сохранении данных возникла ошибка!';
            }
            
            SPIv::I('json')->render($response);
            die();
        }

        // --------------------------------------------------------------------
        // Post insert | modify actions

        if( $status === true && $data['action'] == 'insert' )
        {
            SPIc::I('media')->manage->attach_pack_for_newitem(
                SPI::I('var')->get('media_photo_gid'),
                $item_id
            );

            SPIc::I('media')->manage->attach_pack_for_newitem(
                SPI::I('var')->get('media_audio_gid'),
                $item_id
            );

            SPIc::I('media')->manage->attach_pack_for_newitem(
                SPI::I('var')->get('media_video_gid'),
                $item_id
            );
        }

        // --------------------------------------------------------------------

        $response = array();
        $response['status'] = 'complite';
        $response['link_redirect'] = $this->pack_link( $data['tmode'], array( 'action'=>'view', 'action_complite'=>$data['action'] ) );
        SPIv::I('json')->render($response);
        die();
    }
}
